$(function(){
  $('#goto-register').on('click',()=>{
      $('#register').stop().show()
  })
  $('#goto-login').on('click',()=>{
      $('#register').stop().hide()
  })
   // 验证 用户名 密码
 const { form , layer} = layui
  form.verify ( {
      username:[
          /^[a-z0-9]{6,10}$/,
          '账号名是6到10位由数字, 小写字母组成'
      ],
      password:[
          /^[\S]{6,12}$/,
          '密码必须6到12位，且不能出现空格'
      ],
      repwd:function(value){
      return (value !== $('.pwd').val()) && '两次密码不相同'
      }
     
  })
   

 //注册页
  $('#register .layui-form').on('submit', async (e)=>{
     e.preventDefault();
     // 数据转换成字符串
    const obj = {
        username:$('#register input[name=username]').val(),
        password:$('#register input[name=password]').val()
    } 

    const arr = []
    for(let k in obj){
        arr.push(`${k}=${obj[k]}`)
    }
    const str = arr.join('&')

    const res = await axios({
        method:'post',
        url:'http://api-breakingnews-web.itheima.net/api/reguser',
        data: str
    })
    const { data:{ status ,message}} = res
    if(status === 0){
        layer.msg(message)
        $('#register').stop().hide()
    }
  }) 

  //登录 
  $('#login .layui-form').on('submit', async (e)=>{
      e.preventDefault()
      const obj = {
        username:$('#login input[name=username]').val(),
        password:$('#login input[name=password]').val()
    } 

    const arr = []
    for(let k in obj){
        arr.push(`${k}=${obj[k]}`)
    }
    const str = arr.join('&')

    const res = await axios({
        method:'post',
        url:'http://api-breakingnews-web.itheima.net/api/login',
        data: str
    })
    const { data:{ status ,message}} = res
    if(status === 0){
        layer.msg(message)
        //跳转到index页面
        location.href =`./index.html`
    }
  })



})